package com.itheima.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

 /*   @Autowired
    private HttpSession session;*/// 每次会话是一个对象，也不是单例的。

    // 可以注入！！  单例的对象。始终就只有一个！！ request每次请求又都是一个新的对象。矛盾！！
   /* @Autowired
    private HttpServletRequest request;*/

    //执行添加的时候进行填充
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill .... 开始添加时填充");
        // setCreateTime(LocalDateTime.now());
        this.strictInsertFill(metaObject,
                "createTime",
                LocalDateTime.class,
                LocalDateTime.now());
        //设置更新时间
        this.strictInsertFill(metaObject,
                "updateTime",
                LocalDateTime.class,
                LocalDateTime.now());

        //直接从session中获取当前登陆人id也只可以的。
        // Long eid = (Long) session.getAttribute("employee");
        //从当前线程获取
        Long eid = BaseContext.getCurrentId();
        //设置创建人
        this.strictInsertFill(metaObject,
                "createUser",
                Long.class,
                eid);


        //设置更新人
        this.strictInsertFill(metaObject,
                "updateUser",
                Long.class,
                eid);
    }

    // 执行update修改的时候进行填充
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        //设置更新时间
        this.strictInsertFill(metaObject,
                "updateTime",
                LocalDateTime.class,
                LocalDateTime.now());
        //从当前线程中取出登录用户id
        Long currentId = BaseContext.getCurrentId();
        //设置更新人
        this.strictInsertFill(metaObject,
                "updateUser",
                Long.class,
                currentId);
    }

}
